package metar_taf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class CachedURLLoader {
	private static final MemcacheService MEMCACHE_SERVICE = MemcacheServiceFactory
			.getMemcacheService();
	private URL url;

	public CachedURLLoader(URL url) {
		this.url = url;
	}

	public CachedURLLoader(String url) throws MalformedURLException {
		this.url = new URL(url);
	}

	private InputStream openConnection() throws IOException {
		URLConnection connection = url.openConnection();
		connection.setConnectTimeout(10000);// 10s
		return connection.getInputStream();
	}

	public String load() throws IOException {
		return load(Charset.forName("UTF-8"));
	}

	public String load(Charset charset) throws IOException {
		if (MEMCACHE_SERVICE.contains(url)) {
			String str = (String) MEMCACHE_SERVICE.get(url);
			if (str != null) {
				return str;
			}
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				openConnection(), charset));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null) {
			sb.append(line).append('\n');
		}
		String result = sb.toString();
		MEMCACHE_SERVICE.put(url, result, Expiration.byDeltaSeconds(60 * 15));
		return result;
	}
}
